<?php

/* ----------------------------------------------
  Caloris: Module Contact Editor Detail

  $Id$
  $Author$

  Contact editor with multiple phone numbers and e-mails
  ---------------------------------------------- */

use Nette\Image;

require_once("../../../index.php");
Caloris\ACL::authenticate();

define('_MODULE_ACTIVE', 'contactmanager');

$xmlContacts = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');

$tidy_options = array(
    'input-xml' => true,
    'output-xml' => true,
    'indent' => true,
    'wrap' => false,
);

if ($_REQUEST["action"] == 'contactsEdit') {
    $xma = $xmlContacts->xpath('//contact[@id="' . $_POST["idf"] . '"]');

    if (count($xma) > 0) {
        $xma[0]->name = $_POST["name"];
        $xma[0]->show = Caloris\Tools::checknull($_POST["show"]);
        $xma[0]->post = $_POST["post"];
        $xma[0]->post["show"] = $_POST["post_show"];
        $xma[0]->address = $_POST["address"];
        $xma[0]->city = $_POST["city"];
        $xma[0]->city["show"] = $_POST["city_show"];
        $xma[0]->country = $_POST["country"];
        $xma[0]->country["show"] = $_POST["country_show"];
        $xma[0]->zip = $_POST["zip"];
        $xma[0]->ic = $_POST["ic"];
        $xma[0]->ic["show"] = $_POST["ic_show"];
        $xma[0]->dic = $_POST["dic"];
        $xma[0]->dic["show"] = $_POST["dic_show"];
        $xma[0]->district = $_POST["district"];
        $xma[0]->district["show"] = $_POST["district_show"];

        $xmlContacts->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');
    }

    header("location: " . $_SERVER["HTTP_REFERER"] . "");
    exit();
} elseif ($_REQUEST["function_name"] == 'image_insert') {
    if (Caloris\IO::upload(_CALSET_PATHS_BASE . '/cal-bin/contacts/', $_POST["idf"] . '.jpg') == false) {
        Caloris\IO::remove(_CALSET_PATHS_BASE . '/cal-bin/contacts/' . $_POST["idf"] . '.jpg');
    }

    $image = Image::fromFile(_CALSET_PATHS_BASE . '/cal-bin/contacts/' . $_POST["idf"] . '.jpg');
    $image->resize(100, 150, Nette\Image::EXACT);
    $image->sharpen();
    $image->save(_CALSET_PATHS_BASE . '/cal-bin/contacts/contacts_' . $_POST["idf"] . '.jpg');

    Caloris\IO::remove(_CALSET_PATHS_BASE . '/cal-bin/contacts/' . $_POST["idf"] . '.jpg');

    header("location: " . $_SERVER["HTTP_REFERER"] . "");
    exit();
} elseif ($_REQUEST["function_name"] == 'image_delete') {
    Caloris\IO::remove(_CALSET_PATHS_BASE . '/cal-bin/contacts/contacts_' . $_POST["idf"] . '.jpg');

    if ($_POST["j"] != 1) {
        header("location: " . $_SERVER["HTTP_REFERER"] . "");
        exit();
    } else {
        echo "{\"msg\": \"done\"}";
        exit();
    }
} elseif ($_REQUEST["function_name"] == 'contacts_phone_delete') {
    // Phone delete
    $type = $_POST["type"];
    $id = $_POST["id"];

    $file = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml';
    $xmr = new DOMDOcument;
    $xmr->load($file);

    // Content
    $xpath = new DOMXpath($xmr);

    foreach ($xpath->query('//contact[@id="' . $id . '"]/phone/number[@type="' . $type . '"]') as $node) {
        $node->parentNode->removeChild($node);
    }


    $xmr->save($file);

    if ($_POST["j"] != 1) {
        header("location: " . $_SERVER["HTTP_REFERER"] . "");
        exit();
    } else {
        echo "{\"msg\": \"done\"}";
        exit();
    }
} elseif ($_REQUEST["function_name"] == 'contacts_email_delete') {
    // Email delete
    $type = $_POST["type"];
    $id = $_POST["id"];

    $file = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml';
    $xmr = new DOMDOcument;
    $xmr->load($file);

    // Content
    $xpath = new DOMXpath($xmr);

    foreach ($xpath->query('//contact[@id="' . $id . '"]/emails/email[@type="' . $type . '"]') as $node) {
        $node->parentNode->removeChild($node);
    }

    $xmr->save($file);

    if ($_POST["j"] != 1) {
        header("location: " . $_SERVER["HTTP_REFERER"] . "");
        exit();
    } else {
        echo "{\"msg\": \"done\"}";
        exit();
    }
} elseif ($_REQUEST["function_name"] == 'contacts_email_insert') {
    $type = $_POST["type"];
    $id = $_POST["id"];
    $email = $_POST["email"];

    $xma = $xmlContacts->xpath('//contact[@id="' . $id . '"]/emails/email[@type="' . $type . '"]');

    if (count($xma) > 0) {
        header("location: " . $_SERVER["HTTP_REFERER"] . "");
        exit();
    } else {
        // Insert contact
        $doc = new DOMDOcument;
        $doc->load(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');
        $xpath = new DOMXpath($doc);

        $xmlEmailElementExists = $xmlContacts->xpath('//contact[@id="' . $id . '"]/emails');

        if (count($xmlEmailElementExists) > 0) {
            foreach ($xpath->query('//contact[@id="' . $id . '"]/emails') as $node) {
                $addElement = $doc->createElement('email', $email);
                $node->appendChild($addElement);

                $idAttribute = $doc->createAttribute("type");
                $addElement->appendChild($idAttribute);

                $idAttributeAdmin = $doc->createAttribute("show");
                $addElement->appendChild($idAttributeAdmin);

                $p1 = $doc->createTextNode($_POST["type"]);
                $idAttribute->appendChild($p1);

                $p2 = $doc->createTextNode(1);
                $idAttributeAdmin->appendChild($p2);
            }
        } else {
            foreach ($xpath->query('//contact[@id="' . $id . '"]') as $node) {
                $addElementEmails = $doc->createElement('emails');
                $node->appendChild($addElementEmails);

                $addElement = $doc->createElement('email', $email);
                $addElementEmails->appendChild($addElement);

                $idAttribute = $doc->createAttribute("type");
                $addElement->appendChild($idAttribute);

                $idAttributeAdmin = $doc->createAttribute("show");
                $addElement->appendChild($idAttributeAdmin);

                $p1 = $doc->createTextNode($_POST["type"]);
                $idAttribute->appendChild($p1);

                $p2 = $doc->createTextNode(1);
                $idAttributeAdmin->appendChild($p2);
            }
        }

        $doc->save(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');

        if (class_exists('tidy')) {
            $tidy = new tidy();
            $tidy->parseFile(_CALSET_PATHS_BASE . '/cal-components/data/contacts.xml', $tidy_options, 'utf8');
            $tidy->cleanRepair();

            $xml = simplexml_load_string($tidy);
            $xml->asXML(_CALSET_PATHS_BASE . '/cal-components/data/contacts.xml');
        }
    }

    header("location: " . $_SERVER["HTTP_REFERER"] . "");
    exit();
} elseif ($_REQUEST["function_name"] == 'contacts_phone_insert') {
    $type = $_POST["type"];
    $id = $_POST["id"];
    $phone = $_POST["phone"];

    $xma = $xmlContacts->xpath('//contact[@id="' . $id . '"]/phone/number[@type="' . $type . '"]');

    if (count($xma) > 0) {
        header("location: " . $_SERVER["HTTP_REFERER"] . "");
        exit();
    } else {
        // Insert contact
        $doc = new DOMDOcument;
        $doc->load(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');
        $xpath = new DOMXpath($doc);

        $xmlEmailElementExists = $xmlContacts->xpath('//contact[@id="' . $id . '"]/phone');

        if (count($xmlEmailElementExists) > 0) {
            foreach ($xpath->query('//contact[@id="' . $id . '"]/phone') as $node) {
                $addElement = $doc->createElement('number', $phone);
                $node->appendChild($addElement);

                $idAttribute = $doc->createAttribute("type");
                $addElement->appendChild($idAttribute);

                $idAttributeAdmin = $doc->createAttribute("show");
                $addElement->appendChild($idAttributeAdmin);

                $p1 = $doc->createTextNode($_POST["type"]);
                $idAttribute->appendChild($p1);

                $p2 = $doc->createTextNode(1);
                $idAttributeAdmin->appendChild($p2);
            }
        } else {
            foreach ($xpath->query('//contact[@id="' . $id . '"]') as $node) {
                $addElementEmails = $doc->createElement('phone');
                $node->appendChild($addElementEmails);

                $addElement = $doc->createElement('number', $phone);
                $addElementEmails->appendChild($addElement);

                $idAttribute = $doc->createAttribute("type");
                $addElement->appendChild($idAttribute);

                $idAttributeAdmin = $doc->createAttribute("show");
                $addElement->appendChild($idAttributeAdmin);

                $p1 = $doc->createTextNode($_POST["type"]);
                $idAttribute->appendChild($p1);

                $p2 = $doc->createTextNode(1);
                $idAttributeAdmin->appendChild($p2);
            }
        }

        $doc->save(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');

        if (class_exists('tidy')) {
            $tidy = new tidy();
            $tidy->parseFile(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml', $tidy_options, 'utf8');
            $tidy->cleanRepair();

            $xml = simplexml_load_string($tidy);
            $xml->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/contacts.xml');
        }
    }

    header("location: " . $_SERVER["HTTP_REFERER"] . "");
    exit();
}

$idf = $_REQUEST["idf"];

if ($idf == '') {
    $idf = $_REQUEST["connect"];
    $idfTag .= 'connect';
} else {
    $idf = $_REQUEST["idf"];
    $idfTag .= 'id';
}

$xma = $xmlContacts->xpath('//contact[@' . $idfTag . '="' . $idf . '"]');
$xmr = $xmlContacts->xpath('//contact[@' . $idfTag . '="' . $idf . '"]/phone/number[@type="Domácí"]');

if ($xma[0]->post["show"] == 1) {
    $checkedPost = 'CHECKED';
} else {
    $checkedPost = '';
}

if ($xma[0]->country["show"] == 1) {
    $checkedCountry = 'CHECKED';
} else {
    $checkedCountry = '';
}

// Country List
$xmlCountryListF = simplexml_load_file(_CALSET_PATHS_BASE . '/cal-components/data-public/countries.xml');


$xmlCountryList = $xmlCountryListF->xpath('//core/country[enable/members="0"]');

if (count($xmlCountryList) > 0) {
    for ($c = 0; $c < count($xmlCountryList); $c++) {
        $countryList[] = $xmlCountryList[$c]->translate->cs;
    }
}

/* TODO CALORIS: Selected value + AJAX

  $formContact2 = new Nette\Forms\Form;
  $formContact2->setAction(_CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php');
  $formContact2->addHidden('function_name', 'contacts_edit');
  $formContact2->addHidden('idf', $xma[0]["id"]);
  $formContact2->addText('name', 'Jméno společnosti')
  ->setDefaultValue($xma[0]->name);
  $formContact2->addCheckbox('post_show', 'Ukázat funkci v kontaktech')
  ->setDefaultValue($checkedPost);
  $formContact2->addText('address', 'Adresa')
  ->setDefaultValue($xma[0]->address);
  $formContact2->addText('city', 'Město')
  ->setDefaultValue($xma[0]->city);
  $formContact2->addText('zip', 'PSČ')
  ->setDefaultValue($xma[0]->zip);
  $formContact2->addSelect('country', 'Země')
  ->setItems($countryList, TRUE)->setAttribute("SELECTED");
  $formContact2->addCheckbox('country_show', 'Ukázat zemi v kontaktech')
  ->setDefaultValue($checkedCountry); */

$content .= '<h1>Detail kontaktu</h1>';

if (count($xma[0]) > 0) {
    $content .= '
<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" method="post" class="form-horizontal">
<input type="hidden" name="action" value="contactsEdit"  />
<input type="hidden" name="idf" value="' . $xma[0]["id"] . '"  />
    
<div class="control-group">
<label class="control-label">Jméno</label>
<div class="controls"><input type="text" name="name" value="' . $xma[0]->name . '" class="input-xxlarge" /></div>
</div>

<div class="control-group">
<label class="control-label">Funkce</label>
<div class="controls"><input type="text" name="post" value="' . $xma[0]->post . '" class="input-xxlarge" /><br />
' . Caloris\Tools::answerio($xma[0]->post["show"], 'post_show',0) . ' zobrazit funkci v kontaktech</div>
</div>

<div class="control-group">
<label class="control-label">Adresa</label>
<div class="controls"><input type="text" name="address" value="' . $xma[0]->address . '" class="input-xxlarge" /></div>
</div>

<div class="control-group">
<label class="control-label">Město</label>
<div class="controls"><input type="text" name="city" value="' . $xma[0]->city . '" class="input-xxlarge" /></div>
</div>

<div class="control-group">
<label class="control-label">PSČ</label>
<div class="controls"><input type="text" name="zip" value="' . $xma[0]->zip . '" class="input-large" /></div>
</div>

<div class="control-group">
<label class="control-label">Země</label>
<div class="controls">
<select name="country" id="country">';

    // Loads XML Countries xml file
    $doc = new DOMDOcument;
    $doc->load(_CALSET_PATHS_BASE . '/cal-components/data-public/countries.xml');

    // Filter pedrmitted countries
    $xpath = new DOMXpath($doc);
    $qry = '//core/country[enable/members="0"]';
    $entries = $xpath->query($qry);

    foreach ($entries as $node) {
        $node->parentNode->removeChild($node);
    }

    $xmlCountry = simplexml_load_string($doc->saveXML());
    $xpc = (array) $xmlCountry;
    $xpc = $xpc["country"];
    $xpc = array_values($xpc);

    if (count($xpc) > 0) {
        for ($a = 0; $a < count($xpc); $a++) {
            if (strcmp($xpc[$a]->translate->cs, $xma[0]->country) == 0) {
                $content .= '<option value="' . $xpc[$a]->name . '" selected="selected">' . $xpc[$a]->translate->cs . '</option>';
            } else {
                $content .= '<option value="' . $xpc[$a]->name . '">' . $xpc[$a]->translate->cs . '</option>';
            }
        }
    }

    $content .= '</select><br />' . Caloris\Tools::answerio($xma[0]->country["show"], 'country_show', 0) . ' zobrazit zemi v kontaktech
</div>
</div>

<div class="control-group">
<label class="control-label">Kraj</label>
<div class="controls">
';

    $xmlDistrictsF = simplexml_load_file(_CALSET_PATHS_BASE . '/cal-components/data-public/countries.xml');
    $xmlDistricts = $xmlDistrictsF->xpath('//country[name="' . $xma[0]->country . '"]/districts/district');

    if (count($xmlDistricts) > 0) {
        $content.= '<div id="district" style="display: none;">' . $xma[0]->district . '</div>
<select name="district" id="mnox">
    <option value="">Vyberte kraj</option>            
</select>';
    } else {
        $content.= '
<select name="district" id="mnox">
</select>';
    }

    $content .= '<br />
' . Caloris\Tools::answerio($xma[0]->district["show"], 'district_show',0) . ' zobrazit kraj v kontaktech
</div>
</div>

<div class="control-group">
<label class="control-label">IČ</label>
<div class="controls"><input type="text" name="ic" value="' . $xma[0]->ic . '" class="input-large" /><br />
' . Caloris\Tools::answerio($xma[0]->ic["show"], 'ic_show',0) . ' zobrazit IČ v kontaktech</div>
</div>

<div class="control-group">
<label class="control-label">DIČ</label>
<div class="controls"><input type="text" name="dic" value="' . $xma[0]->dic . '" class="input-large" /><br />
' . Caloris\Tools::answerio($xma[0]->dic["show"], 'dic_show',0) . ' zobrazit DIČ v kontaktech</div>
</div>

<div class="control-group">
<label class="control-label">Ukázat kontakt</label>
<div class="controls">' . Caloris\Tools::answerio($xma[0]->show, 'show',0) . '</div>
</div>

<div class="control-group">
    <div class="controls"><button type="submit" class="btn btn-primary">Uložit</button>  ' . $xma[0]->date->created . '</div>
</div>
</form>' . PHP_EOL;
}
$content .= '
<h2>E-maily</h2>

<table class="table table-striped">
    <tr> 
        <td style="width: 20px;">&nbsp;</td>
        <td style="width: 250px;">Typ</td>
        <td>E-mail</td>
    </tr>
    <tr> 
        <td style="width: 20px;">
<form id="rpp" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" method="post">
<input type="hidden" name="function_name" value="contacts_email_insert" /><input type="submit" value="Vložit" class="btn btn-primary" />
<input type="hidden" name="id" value="' . $idf . '"/></td>
        <td style="width: 250px;"><input type="text" name="type" class="input-xxlarge" /></td>
        <td><input type="text" name="email" class="input-xxlarge" /></form></td>
    </tr>' . PHP_EOL;

for ($a = 0; $a < count($xma[0]->emails->email); $a++) {
    $deleteEmail = '
<form id="formshw_' . $a . '" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" method="post" name="trbl_' . $a . '" onsubmit="return false;">
<input type="hidden" name="function_name" value="contacts_email_delete" />
<input type="hidden" name="type" value="' . $xma[0]->emails->email[$a]["type"] . '" /><input type="hidden" name="id" value="' . $idf . '" />
<input type="submit" id="formx_' . $a . '" value="Smazat" class="btn btn-danger" />
</form>	
';

    $content .= '<tr id="trbl_' . $a . '">
        <td>' . $deleteEmail . '</td>
        <td>' . $xma[0]->emails->email[$a]["type"] . '</td>
        <td>' . $xma[0]->emails->email[$a] . '</td>
    </tr>' . PHP_EOL;
}

$content .= '
</table>

<h2>Telefony</h2>

<table class="table table-striped">
        <td style="width: 20px;">
<form id="rpp" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" method="post" style="margin: 0;">
<input type="hidden" name="function_name" value="contacts_phone_insert" /><input type="submit" value="Vložit" class="btn btn-primary" />
<input type="hidden" name="id" value="' . $idf . '"/></td>
        <td style="width: 250px;"><input type="text" name="type" class="input-xxlarge" /></td>
        <td><input type="text" name="phone" class="input-xxlarge" /></form></td>
    </tr>' . PHP_EOL;

for ($a = 0; $a < count($xma[0]->phone->number); $a++) {
    $deletePhone = '
<form id="formshww_' . $a . '" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" method="post" name="trbc_' . $a . '" onsubmit="return false;">
<input type="hidden" name="function_name" value="contacts_phone_delete" /><input type="hidden" name="id" value="' . $idf . '" />
<input type="hidden" name="type" value="' . $xma[0]->phone->number[$a]["type"] . '" />
<input type="submit" id="formx_' . $a . '" value="Smazat" class="btn btn-danger" />
</form>' . PHP_EOL;

    $content .= '<tr id="trbc_' . $a . '">
        <td style="width: 20px;">' . $deletePhone . '</td>
        <td style="width: 250px;">' . $xma[0]->phone->number[$a]["type"] . '</td>
        <td>' . $xma[0]->phone->number[$a] . '</td>
    </tr>' . PHP_EOL;
}

$content .= '
</table>' . PHP_EOL;

$content .= '<h2>Seznam obrázků pro tento kontakt</h2>' . PHP_EOL;

if (file_exists(_CALSET_PATHS_BASE . '/cal-bin/contacts/contacts_' . $idf . '.jpg')) {
    $content .= '
<div id="trbc_' . $a . '"><a href="' . _CALSET_PATHS_URI . '/cal-bin/contacts/contacts_' . $idf . '.jpg"><img src="' . _CALSET_PATHS_URI . '/cal-bin/contacts/contacts_' . $idf . '.jpg" alt="' . $idf . '" /></a>
<form id="formshw_' . $a . '" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" name="trbc_' . $a . '" method="post" onsubmit="return false;">
<input type="hidden" name="function_name" value="image_delete"  />
<input type="hidden" name="idf" value="' . $idf . '"  />
<input type="submit" id="formx_' . $a . 'c" class="btn btn-danger" value="Smazat" />
</form>
</div>' . PHP_EOL;
}

$content .= '
<form id="rsc" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/contacts.detail.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="function_name" value="image_insert"  />
<input type="hidden" name="idf" value="' . $idf . '"  />
    
<div class="control-group">
<label class="control-label">Soubor</label>
<div class="controls"><input name="the_file" type="file" size="25" /></div>
</div>

<div class="control-group">
<div class="controls"><input type="submit" value="Přidat" class="btn btn-primary" /></div>
</div>
</form>' . PHP_EOL;


$content .= '<div style="clear: left;"></div>' . PHP_EOL;

// Testing existence of username
$xmlUser = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
$xmlUserCheck = $xmlUser->xpath('//user[@id="' . $idf . '"]');

if (count($xmlUserCheck) > 0) {
    $content .= '
        <p><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/contactmanager/users.detail.php?idf=' . $idf . '">Editovat přiřazeného uživatele</a></p>';
}

$data["title"] = 'Kontakty: Detailní popis kontaktu';

$tmpl = new Caloris\Template;
$tmpl->input($content);
$tmpl->renderHead($data);
echo $tmpl->renderBody('caloris-admin');